package com.qiguliuxing.dts.merchant.controller;
import java.util.*;
import javax.validation.constraints.NotNull;

import com.qiguliuxing.dts.common.constant.ApiAdminConsts;
import com.qiguliuxing.dts.common.constant.LogParamsConsts;
import com.qiguliuxing.dts.core.annotation.aoplog.WebLog;
import com.qiguliuxing.dts.db.bean.SeckillGoodsAllinone;
import com.qiguliuxing.dts.db.bean.SeckillGoodsVo;
import com.qiguliuxing.dts.db.bean.TimeBatchConfig;
import com.qiguliuxing.dts.db.domain.DtsGoodsProduct;
import com.qiguliuxing.dts.db.domain.DtsSeckillGoods;
import com.qiguliuxing.dts.merchant.annotation.RequiresPermissionsDesc;
import com.qiguliuxing.dts.merchant.support.AuthSupport;
import com.qiguliuxing.dts.merchant.support.MerchantResponseCode;
import com.qiguliuxing.dts.merchant.support.MerchantResponseUtils;
import com.qiguliuxing.dts.service.base.DtsGoodsProductService;
import com.qiguliuxing.dts.service.base.DtsGoodsSeckillService;
import com.qiguliuxing.dts.service.base.DtsTimeListService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.github.pagehelper.PageInfo;
import com.qiguliuxing.dts.common.util.ResponseUtils;
import com.qiguliuxing.dts.core.validator.Order;
import com.qiguliuxing.dts.core.validator.Sort;

/**
 * 秒杀配置接口
 * @author 1197673878@qq.com
 * @since 1.0.0
 */
@RestController
@RequestMapping("/merchant/seckill")
@Validated
@Api(tags = ApiAdminConsts.Admin.PARENT)
public class MerchantSeckillController {
    private static final Logger logger = LoggerFactory.getLogger(MerchantSeckillController.class);

    @Autowired
    private DtsTimeListService dtsTimeListService;
    @Autowired
    private DtsGoodsSeckillService dtsGoodsSeckillService;
    @Autowired
    private DtsGoodsProductService dtsGoodsProductService;


    @RequiresPermissions("merchant:seckill:list")
    @RequiresPermissionsDesc(menu = { "推广管理", "秒杀管理" }, button = "查询")
    @ApiOperation(value = ApiAdminConsts.Seckill.LIST)
    @GetMapping("/list")
    @WebLog(description = ApiAdminConsts.Seckill.LIST, excludes = {LogParamsConsts.RESPONSE})
    public Object list(@ApiParam(value = "商品id") String goodsId,
                       @ApiParam(value = "页码", defaultValue = "1") @RequestParam(defaultValue = "1") Integer page,
                       @ApiParam(value = "分页大小", defaultValue = "10") @RequestParam(defaultValue = "10") Integer limit,
                       @ApiParam(value = "排序字段", defaultValue = "add_time") @Sort @RequestParam(defaultValue = "add_time") String sort,
                       @ApiParam(value = "排序规则", defaultValue = "desc") @Order @RequestParam(defaultValue = "desc") String order) {
        long total = 0L;
        Map<String, Object> param = new HashMap<String, Object>(16);
        param.put("goodsId", goodsId);
        param.put("offset", page);
        param.put("limit", limit);
        param.put("sort", sort);
        param.put("order", order);
        //数据权限控制,查询当前用户的所属的商户id,brand_id-->good_id
        List<Integer> brandIds = new ArrayList<Integer>();
        brandIds.add(AuthSupport.merchantBrandId());
        List<SeckillGoodsVo> rulesList = null;
        param.put("brandIds", brandIds);
        rulesList = dtsGoodsSeckillService.selectAllSeckillGoods(param);

        total = PageInfo.of(rulesList).getTotal();
        Map<String, Object> data = new HashMap<>(16);
        data.put("total", total);
        data.put("items", rulesList);
        return ResponseUtils.ok(data);
    }

    @RequiresPermissions("merchant:seckill:update")
    @RequiresPermissionsDesc(menu = {"推广管理", "秒杀管理"}, button = "编辑")
    @PostMapping("/update")
    @ApiOperation(value = ApiAdminConsts.Seckill.UPDATE)
    @WebLog(description = ApiAdminConsts.Seckill.UPDATE, persistence = true)
    public Object update(@RequestBody SeckillGoodsAllinone seckillGoods) {
        Object error = dtsGoodsSeckillService.validateSeckillGoodsConf(seckillGoods);
        if (error != null) {
            return error;
        }
        if (dtsGoodsSeckillService.seckillDoing(seckillGoods.getSeckillGoods().getId())) {
            logger.error("推广管理->秒杀管理->编辑错误:{}", MerchantResponseCode.SECKILL_ACTIVE_RUN.desc());
            return MerchantResponseUtils.fail(MerchantResponseCode.SECKILL_ACTIVE_RUN);
        }
        return dtsGoodsSeckillService.update(seckillGoods);
    }

    @RequiresPermissions("merchant:seckill:create")
    @RequiresPermissionsDesc(menu = {"推广管理", "秒杀管理"}, button = "添加")
    @PostMapping("/create")
    @ApiOperation(value = ApiAdminConsts.Seckill.CREATE)
    @WebLog(description = ApiAdminConsts.Seckill.CREATE, persistence = true)
    public Object create(@RequestBody SeckillGoodsAllinone seckillGoods) {
        Object error = dtsGoodsSeckillService.validateSeckillGoodsConf(seckillGoods);
        if (error != null) {
            return error;
        }
        if (dtsGoodsSeckillService.existSeckillGoods(seckillGoods.getSeckillGoods().getGoodsId())) {
            logger.error("推广管理->秒杀管理->添加错误:{}",MerchantResponseCode.EXIST_SECKILL_ACTIVE.desc());
            return MerchantResponseUtils.fail(MerchantResponseCode.EXIST_SECKILL_ACTIVE);
        }
        return dtsGoodsSeckillService.create(seckillGoods);
    }

    /**
     * 结束商品秒杀与删除不同：
     *  结束不需管秒杀是否进行，强制结束，商品设置结束时间，且清理秒杀剩余库存数据
     * @param seckillGoods
     * @return
     */
    @RequiresPermissions("merchant:seckill:finish")
    @RequiresPermissionsDesc(menu = {"推广管理", "秒杀管理"}, button = "结束秒杀")
    @ApiOperation(value = ApiAdminConsts.Seckill.FINISH)
    @PostMapping("/finish")
    @WebLog(description = ApiAdminConsts.Seckill.FINISH, persistence = true)
    public Object finish(@RequestBody DtsSeckillGoods seckillGoods) {
        Integer goodsId = seckillGoods.getGoodsId();
        if (Objects.isNull(goodsId)) {
            return ResponseUtils.badArgument();
        }
        return dtsGoodsSeckillService.finish(seckillGoods);
    }

    @RequiresPermissions("merchant:seckill:delete")
    @RequiresPermissionsDesc(menu = {"推广管理", "秒杀管理"}, button = "删除")
    @ApiOperation(value = ApiAdminConsts.Seckill.DELETE)
    @PostMapping("/delete")
    @WebLog(description = ApiAdminConsts.Seckill.DELETE, persistence = true)
    public Object delete(@RequestBody DtsSeckillGoods seckillGoods) {
        Integer goodsId = seckillGoods.getGoodsId();
        if (Objects.isNull(goodsId)) {
            return ResponseUtils.badArgument();
        }
        if (dtsGoodsSeckillService.seckillDoing(seckillGoods.getId())) {
            logger.error("推广管理->秒杀管理->删除错误:{}",MerchantResponseCode.SECKILL_ACTIVE_RUN.desc());
            return MerchantResponseUtils.fail(MerchantResponseCode.SECKILL_ACTIVE_RUN);
        }
        return dtsGoodsSeckillService.delete(seckillGoods);
    }

    @PostMapping("/getBatchConfig")
    @ApiOperation(value = "获取秒杀批次时间配置信息")
    public Object getBatchConfig() {
        Map<String, Object> map = new HashMap<>(16);
        List<TimeBatchConfig> list = dtsTimeListService.selectBatchConfig(map);
        Map<String, Object> data = new HashMap<>(16);
        data.put("batchList", list);
        return ResponseUtils.ok(data);
    }

    /**
     * 商品详情
     *
     * @param id
     * @return
     */
    @RequiresPermissions("merchant:seckill:read")
    @RequiresPermissionsDesc(menu = { "推广管理", "秒杀管理" }, button = "货品详情")
    @ApiOperation(value=ApiAdminConsts.Seckill.READ)
    @GetMapping("/detailProduct")
    @WebLog(description = ApiAdminConsts.Seckill.READ)
    public Object detailProduct(@ApiParam(value = "商品id") @NotNull Integer id) {
        List<DtsGoodsProduct> dtsGoodsProducts = dtsGoodsProductService.queryByGid(id);
        Map<String, Object> data = new HashMap<>();
        data.put("products", dtsGoodsProducts);
        return ResponseUtils.ok(data);
    }

    /**
     * 商品详情
     *
     * @param id
     * @return
     */
    @RequiresPermissions("merchant:seckill:read")
    @RequiresPermissionsDesc(menu = { "推广管理", "秒杀管理" }, button = "详情")
    @ApiOperation(value=ApiAdminConsts.Seckill.READ)
    @GetMapping("/detail")
    @WebLog(description = ApiAdminConsts.Seckill.READ)
    public Object detail(@ApiParam(value = "商品id") @NotNull Integer id) {
        return dtsGoodsSeckillService.detail(id);
    }
}
